package edu.msg.hrappy.backend.service.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import edu.msg.hrappy.backend.repository.exception.RepositoryException;

/**
 * @author Torok Eniko
 *         This class is used for encrypting a string
 */
public final class Encryption {
    private static final int ENCNR = 16;
    
    private Encryption () {
        // CONSTR
    }
    
    /**
     * @param password
     *            - a string that needs to be encrypted
     * @return a string which contains 38 hexadecimal numbers generated by the encryption of the password
     */
    
    public static String encrypt (final String password) {
        String output = null;
        try {
            MessageDigest md = MessageDigest.getInstance ("SHA-256");
            md.update (password.getBytes ("UTF-8"));
            /*
             * byte[] digest = md.digest ();
             * BigInteger bigInt = new BigInteger (1, digest);
             * output = bigInt.toString (ENCNR);
             */
            byte[] digest = md.digest ();
            StringBuffer sb = new StringBuffer ();
            for (int i = 0; i < digest.length; i++) {
                String hex = Integer.toHexString (0xff & digest[i]);
                if (hex.length () == 1)
                    sb.append ('0');
                sb.append (hex);
            }
            output = sb.toString ();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            throw new RepositoryException ("Exception in Encryption" + ex);
        }
        return output;
    }
    
}
